package com.zhan.ielts.web.controller;

import com.zhan.frame.core.web.domain.Result;
import com.zhan.ielts.domain.Topic;
import com.zhan.ielts.service.ParamService;
import com.zhan.ielts.service.TopicService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/topicHandle")
public class TopicHandleController {

    private Logger log = LoggerFactory.getLogger(TopicController.class);

    @Autowired
    private TopicService topicService;

    @Autowired
    private ParamService paramService;


    @ResponseBody
    @RequestMapping(value = "/delete")
    public Result delete(String id) {
        Result result = new Result();
        if (StringUtils.isEmpty(id)) {
            result.addError("参数错误");
            return result;
        }
        try {
            topicService.deleteTopicCascade(id);
            result.addOK("删除成功");
        } catch (Exception e) {
            log.error("级联删除topic出错:", e);
            result.addError("删除出错");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteList")
    public Result deleteList(String[] ids) {
        Result result = new Result();
        try {
            topicService.deleteTopicListCascade(ids);
            result.addOK("删除成功");
        } catch (Exception e) {
            log.error("级联删除topicList出错:", e);
            result.addError("删除出错");
        }
        return result;
    }

    @RequestMapping(value = "/update")
    public String update(Topic topic , Model model) {
        try {
            topic.setRemoteVersion(topic.getRemoteVersion()+1);
            topic.setUpdateTime(String.valueOf(System.currentTimeMillis()));
            topicService.updateByIdSelective(topic);
        } catch (Exception e) {
            log.error("updateTopic出错:", e);
        }
        model.addAttribute("topicCode",topic.getTopicCode());
        return "redirect:/topic";
    }

    @ResponseBody
    @RequestMapping(value = "/updateVersion")
    public Result updateVersion(String part) {
        Result result = new Result();
        try {
            paramService.updateVersion(part);
            result.addOK("更新成功");
        } catch (Exception e) {
            log.error("更新{}版本号param出错:", part, e);
            result.addError("更新失败");
        }
        return result;
    }
}